package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgxd.entity.pojo.HumHistoryEntity;
import com.hgxd.entity.res.ResHumHistory;
import com.hgxd.entity.vo.HumHistoryVo;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.HumHistoryDao;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.HumHistoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author: wtf
 * @Description: 温度计历史记录
 * @Date: 2022/10/20/11:14
 */
@Service("HumHistoryService")
public class HumHistoryServiceImpl extends ServiceImpl<HumHistoryDao, HumHistoryEntity> implements HumHistoryService {

    @Resource
    private HumHistoryDao humHistoryDao;

    @Override
    public List<HumHistoryEntity> getNewHumByCntrNo(String cntrNo) {
        if ("".equals(cntrNo)) {
            throw new ServiceException(ResultCodeEnum.PARAMETER_IS_EMPTY, "参数为空");
        }
        LambdaQueryWrapper<HumHistoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HumHistoryEntity::getCntrNo, cntrNo);
        //获取该柜号下所有的温度传感器id
        List<Integer> list = humHistoryDao.selectList(queryWrapper).stream()
                .map(HumHistoryEntity::getHumId).distinct()
                .collect(Collectors.toList());
        ArrayList<HumHistoryEntity> resultList = new ArrayList<>();
        // 根据humId查询对应最新数据
        for (Integer humId : list) {
            resultList.add(getNewByHumId(humId));
        }
        return resultList;
    }

    @Override
    public Map<Integer, List<ResHumHistory>> getDataByTimeAndCntrNo(HumHistoryVo humHistoryVo) {
        HashMap<Integer, List<ResHumHistory>> map = new HashMap<>();
        for (int i = 1; i <= 3; i++) {
            map.put(i, humHistoryDao.getDataByTimeAndCntrNo(humHistoryVo.getCntrNo(), i + "", humHistoryVo.getTime()));
        }
        return map;
    }

    private HumHistoryEntity getNewByHumId(int humId) {
        LambdaQueryWrapper<HumHistoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HumHistoryEntity::getHumId, humId)
                .orderByDesc(HumHistoryEntity::getUpdateTime);
        return humHistoryDao.selectList(queryWrapper).get(0);
    }
}
